var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var placeSearch, txtEnderecoPartida;
var placeSearch, txtEnderecoChegada;
var markerArray = [];
var stepDisplay;

var componentForm = {
	street_number : 'short_name',
	route : 'long_name',
	locality : 'long_name',
	administrative_area_level_1 : 'short_name',
	country : 'long_name',
	postal_code : 'short_name'
};

function initialize() {
	txtEnderecoPartida = new google.maps.places.Autocomplete((document
			.getElementById('txtEnderecoPartida')), {
		types : [ 'geocode' ]
	});

	txtEnderecoChegada = new google.maps.places.Autocomplete((document
			.getElementById('txtEnderecoChegada')), {
		types : [ 'geocode' ]
	});

	google.maps.event.addListener(txtEnderecoPartida, 'place_changed',
			function() {
				obterNumeroPartida();
			});

	google.maps.event.addListener(txtEnderecoChegada, 'place_changed',
			function() {
				obterNumeroChegada();
			});

	directionsDisplay = new google.maps.DirectionsRenderer();
	var latlng = new google.maps.LatLng(-23.5690094, -46.63987309999999);

	var options = {
		zoom : 13,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("mapa-simulado"), options);
	directionsDisplay.setMap(map);
	directionsDisplay.setOptions( { suppressMarkers: true } );
	stepDisplay = new google.maps.InfoWindow();
	
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {

			pontoPadrao = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);
			map.setCenter(pontoPadrao);

			var geocoder = new google.maps.Geocoder();
		});
	}
}

function calculaCorrida() {
    limpar();
    var enderecoPartida = $("#txtEnderecoPartida").val();
	var enderecoChegada = $("#txtEnderecoChegada").val();
	var request;
	if ($("#incluirVolta").prop("checked")) {
		request = {
			origin : enderecoPartida,
			destination : enderecoPartida,
			waypoints: [{location: enderecoChegada }],
			travelMode : google.maps.TravelMode.DRIVING
		};
	} else {
		request = {
			origin : enderecoPartida,
			destination : enderecoChegada,
			travelMode : google.maps.TravelMode.DRIVING
		};
	}
	directionsService.route(request, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(result);
			showSteps(result);
			setTerminoValorDistancia(result);
		} else {
			//Tratamento de Erro
		}
	});
}

function limpar() {
	for (i = 0; i < markerArray.length; i++) {
      markerArray[i].setMap(null);
    }
    markerArray = [];
}


function showSteps(directionResult) {
	var myRoute = directionResult.routes[0].legs[0];
	
	var marker = new google.maps.Marker({
		position : myRoute.steps[0].start_point,
		map : map,
		icon : "/recursos/img/maps/darkgreen_MarkerA.png"
	});
	markerArray.push(marker);
	
	var marker = new google.maps.Marker({
		position : myRoute.steps[myRoute.steps.length - 1].end_point,
		map : map,
		icon : "/recursos/img/maps/red_MarkerB.png"
	});
	markerArray.push(marker);
}

function setTerminoValorDistancia(result) {
	var total = 0;
	var duration = 1200;
	var myroute = result.routes[0];
	for (var i = 0; i < myroute.legs.length; i++) {
		total += myroute.legs[i].distance.value;
		duration += myroute.legs[i].duration.value;
	}
	total = total / 1000.0;
	var termino = rectime(duration);
	document.getElementById("distancia").innerHTML = total + " km";
	document.getElementById("termino").innerHTML = termino;
	document.getElementById("valor").innerHTML = "R$ 22,00";
	
	/*var form = $("#formSimulacao");
	var url = "/calculaValor";
	ajaxPOST(url, form, calculaValor, error);*/
}

function calculaValor (resultado) {
	$("#valor").innerHTML = "R$ " + resultado;
}

function rectime(sec) {
	var hr = Math.floor(sec / 3600);
	var min = Math.floor((sec - (hr * 3600)) / 60);
	sec -= ((hr * 3600) + (min * 60));
	sec += '';
	min += '';
	while (min.length < 2) {
		min = '0' + min;
	}
	while (sec.length < 2) {
		sec = '0' + sec;
	}
	hr = (hr) ? hr + ':' : '';
	return hr + min + ':' + sec;
}

function localizaEnderecoPartida() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			var geolocation = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);
			var circle = new google.maps.Circle({
				center : geolocation,
				radius : position.coords.accuracy
			});
			txtEnderecoPartida.setBounds(circle.getBounds());
		});
	}
}

function obterNumeroPartida() {
	var enderecoPartida = document.getElementById("txtEnderecoPartida").value;
	var numPartida = "";
	if (enderecoPartida != "") {
		var place = txtEnderecoPartida.getPlace();
		if (place != null && place.address_components != null) {
			for (var i = 0; i < place.address_components.length; i++) {
				var addressType = place.address_components[i].types[0];
				if (addressType == "street_number") {
					numPartida = place.address_components[i][componentForm[addressType]];
				}
			}
			document.getElementById("txtNumeroPartida").value = numPartida;
			if (enderecoPartida == "" || numPartida == "") {
				document.getElementById("txtNumeroPartida").disabled = false;
			} else {
				document.getElementById("txtNumeroPartida").disabled = true;
			}
		} else {
			document.getElementById("txtNumeroPartida").value = numPartida;
			document.getElementById("txtNumeroPartida").disabled = false;
		}

	} else {
		document.getElementById("txtNumeroPartida").value = numPartida;
		document.getElementById("txtNumeroPartida").disabled = false;
	}
}

function obterNumeroChegada() {
	var enderecoChegada = document.getElementById("txtEnderecoChegada").value;
	var numChegada = "";
	if (enderecoChegada != "") {
		var place = txtEnderecoChegada.getPlace();
		if (place != null && place.address_components != null) {
			for (var i = 0; i < place.address_components.length; i++) {
				var addressType = place.address_components[i].types[0];
				if (addressType == "street_number") {
					numChegada = place.address_components[i][componentForm[addressType]];
				}
			}
			document.getElementById("txtNumeroChegada").value = numChegada;
			if (enderecoChegada == "" || numChegada == "") {
				document.getElementById("txtNumeroChegada").disabled = false;
			} else {
				document.getElementById("txtNumeroChegada").disabled = true;
			}
		} else {
			document.getElementById("txtNumeroChegada").value = numChegada;
			document.getElementById("txtNumeroChegada").disabled = false;
		}

	} else {
		document.getElementById("txtNumeroChegada").value = numChegada;
		document.getElementById("txtNumeroChegada").disabled = false;
	}
}

function localizaEnderecoChegada() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			var geolocation = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);
			var circle = new google.maps.Circle({
				center : geolocation,
				radius : position.coords.accuracy
			});
			txtEnderecoChegada.setBounds(circle.getBounds());
		});
	}
}